<script setup lang="ts">
import { ref, type Ref } from 'vue'
import { useContextMenu } from '../utils/useContextMenu'
interface Item {
  label: string
}
defineProps({
  items: {
    type: Array<Item>,
    default: () => []
  }
})
const emit = defineEmits(['select'])
const containerRef = ref<HTMLElement>()
const { x, y, visiable } = useContextMenu(containerRef as Ref<HTMLElement>)

const handlebeforeEnter = (el: Element) => {
  const htmlEl = el as HTMLElement
  htmlEl.style.height = '0'
}
const handleClick = (item: Item) => {
  emit('select', item)
}

const handleEnter = (el: Element) => {
  const htmlEl = el as HTMLElement
  htmlEl.style.height = 'auto'
  const h = htmlEl.clientHeight
  htmlEl.style.height = '0'
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      htmlEl.style.height = h + 'px'
      htmlEl.style.transition = '0.3s'
    })
  })
}
const handleAfterEnter = (el: Element) => {
  const htmlEl = el as HTMLElement
  htmlEl.style.transition = 'none'
}
</script>
<template>
  <div ref="containerRef" class="vivid-context-menu-container">
    <slot></slot>

    <teleport to="body">
      <transition @before-enter="handlebeforeEnter" @enter="handleEnter" @after-enter="handleAfterEnter">
        <div v-if="visiable" class="vivid-context-menu" :style="{ left: x + 'px', top: y + 'px' }">
          <div class="menu-list">
            <div class="menu-item" v-for="item in items" :key="item.label" @click="handleClick(item)">{{
              item.label }}</div>
          </div>
        </div>
      </transition>
    </teleport>

  </div>
</template>


<style scoped>
.vivid-context-menu {
  position: fixed;
  background: rgba(30, 30, 40, 0.95);
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(10px);
  overflow: hidden;
  z-index: 1000;
  min-width: 200px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.menu-list {
  padding: 8px 0;
}

.menu-item {
  padding: 12px 20px;
  color: #e0e0e0;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
  transition: all 0.2s ease;
}

.menu-item:hover {
  background: rgba(80, 100, 220, 0.5);
  color: white;
}
</style>
